<template>
  <Page name="转账">
    <nuxt-link :to="'/accept/list?idx=0&id='+userInfo.account" slot="right" class="text-primary header-link">转账记录</nuxt-link>
    <div class="info-card fxv-center">
      <div class="avatar" v-if="userInfo.avatar">
        <img :src="userInfo.avatar">
      </div>
      <div class="name">{{userInfo.name}}</div>
      <div class="account">{{userInfo.account}}</div>
      <div class="check">
        <div v-if="!hasCheck" @click="checkUserStatus = true">点此验证</div>
        <div v-else class="ok fx fx-vc"><i class="ic ic-tip-yellow mr12"></i> 验证已通过</div>
      </div>
    </div>

    <form @keypress.enter="submit" onsubmit="return false">
      <div class="form-card">
        <div class="item fx fx-vc fx-between"  @click="showActionSheet=true">
          <div class="label">转账资金币种</div>
          <div class="right">
            <div class="fx-center">
              <span class="currency mr12" :class="{'currency-empty':!currency_code}">{{currency_code || '请选择'}}</span>
              <i class="css-arrow-right"></i>
            </div>
          </div>
        </div>

        <div class="amount-box">
          <div class="item fxv momey-item">
            <div class="label">转账金额</div>
            <Input
              v-model="amount"
              type="text"
              filter="float"
              placeholder="请输入想要转账的金额"
              @focus="checkCurrency"
              @blur="checkAmount"/>
          </div>
          <div class="item">
            <Input v-model="remark" placeholder="添加备注(50字以内)" maxlength="50"/>
          </div>
          <div class="tip-box" v-if="amountTip && amount">
            <div class="tip-alert error">
              <i class="tip-icon"></i>
              <p>余额不足，基于您的会员等级，乐钱包账户的各种币种金额和市场汇率，本次最高只能转{{this.pay_group.usable.amount}} {{this.currency_code}}。<nuxt-link to="/wealth/recharge">去充值</nuxt-link></p>
            </div>
          </div>
        </div>
        <div class="item fx fx-vc fx-between mt20">
          <div class="label">资金扣除组合</div>
          <div class="right">
            <div class="fx-center">
              <span class="currency">资金扣除组合</span>
              <i class="arrow"></i>
            </div>
          </div>
        </div>
        <div class="item fx fx-vc fx-between" v-if="pay_group.list && pay_group.list.length && pay_group.usable.state < 2 && amount">
          <div class="label">
            <span v-for="(item,index) in pay_group.list" :key="index">{{index >0 ? '+' : ''}}{{item.amount}} {{item.currency_code}}</span>
          </div>
        </div>
      </div>
      <div class="form-btn">
        <button type="button" :disabled="!formValid || posting || lock" class="btn btn-primary btn-block submit" @click="submit">确认转账</button>
      </div>
    </form>

    <ActionSheet
      v-if="showActionSheet"
      title="请选择转账币种"
      :list="currencys"
      :value="currency_code"
      @close="showActionSheet = false"
      @select="changeCurrency"
      />

      <Alert title="验证对方乐马名称" @close="checkUserStatus=false,checkUserName=''" @ok="checkUser" v-if="checkUserStatus">
        <div slot="content">
          <div class="check-name-box">
            <input type="text" v-model="checkUserName" @keypress.enter="checkUser" placeholder="请补全对方乐马名称">
            <div>{{userInfo.name}}</div>
          </div>
        </div>
      </Alert>
  </Page>
</template>

<script>
import Page from '~/components/page'
import Input from '~/components/Input'
import ActionSheet from '~/components/ActionSheet'
import Alert from '~/components/Alert'
export default {
  components:{
    Page,
    Input,
    ActionSheet,
    Alert
  },
  validate({store,redirect}){
    // 如果userInfo为空，表示没有经过上一步操作非法进入页面
    if(!store.state.accept.userInfo){
      redirect('/accept')
    }
    return true;
  },
  async asyncData({store}){
    await store.dispatch('accept/checkWallets');
    let {
      currency_code = '',
      amount = '',
      remark = '',
      hasCheck = false,
      amountTip = false,
      lock = true, //当余额不足等其他情况是，需要锁住不给提交
      pay_group = {},
    } = store.state.accept.form || {};
    return {
      currency_code,
      amount,
      hasCheck,
      remark,
      lock,
      pay_group,
      amountTip,
      userInfo: store.state.accept.userInfo,
      wallets:store.state.accept.wallets,
      currencys: store.state.currencys.map(item=>{
        return {
          value:item.code,
          label:item.name
        }
      })
    }
  },
  data(){
    return {
      checkUserLoading:false,
      checkUserStatus:false,
      checkUserName:'',
      posting:false,
      showActionSheet:false,
    }
  },
  computed: {
    formValid(){
      return String(this.currency_code).trim() && String(this.amount).trim();
    }
  },
  methods:{
    changeCurrency(item){ // 币种切换 清除金额，提示，资金组合
      this.currency_code = item.value;
      this.amount = '';
      this.amountTip = false;
      this.pay_group = {};
      this.lock = true;
    },
    async submit(){
      if(this.posting || this.lock) return false;

      this.$store.commit('accept/setForm',{
        amount:this.amount,
        remark:this.remark,
        currency_code:this.currency_code,
        pay_group:this.pay_group,
        hasCheck:this.hasCheck,
        amountTip:this.amountTip,
        lock:this.lock,
      })
      this.$router.push({name:'accept-confirm'})
    },
    checkCurrency(e){ // 检查是否已选币种
      if(!String(this.currency_code).trim()){
        this.$toast('请先选择转账到资金币种')
        e.target.blur();
      }
    },
    async checkAmount(e){ // 检查输入金额是否有效
      if(this.currency_code && this.amount){
        await this.getPayGroup();
        this.amountTip = false;
        this.lock = false;

        switch(Number(this.pay_group.usable.state)){
          case 0: //可用
            break;
          case 1: // 当前币种余额不够
            this.$alert(`该币种余额不足，使用其他币种进行兑换最高可转${this.pay_group.usable.amount} ${this.currency_code}`);
            break;
          case 2: // 资金组合不够
            this.amountTip = true;
            this.lock = true;
            break;
        }
      }
    },
    getBalanceByCurrency(code){ //获取当前币种余额
      let balance = null;
      if(code){
        let item = this.wallets.find(item=>item.currency_code == code)
        if(item){
          balance = item.amount;
        }
      }
      return balance;
    },
    async checkUser(){// 检测用户是否匹配
      if(this.checkUserLoading || !String(this.checkUserName).trim()) return false;
      this.checkUserLoading = true;

      let {data:rs} = await this.$axios.post('?ct=api&ac=verify_name',{
        account:this.userInfo.account,
        name:this.checkUserName
      })

      if(rs.code == 0){
        this.hasCheck = true;
      }else{
        this.$toast(rs.msg);
      }
      this.checkUserLoading = false;
      this.checkUserStatus = false;
    },
    async getPayGroup(){ // 获取扣款组合
      try{
        if(this.posting) return false;
        this.posting = true;
        let { data: rs } = await this.$axios.post('?ct=api&ac=pay_group',{
          amount:this.amount,
          currency_code:this.currency_code
        });
        if(rs.code == 0){
          this.pay_group = rs.data;
        }else{
          this.$toast(rs.msg);
        }
      }catch(e){
        this.$toast('获取组合接口出错');
        this.$error(e);
      }
      this.posting = false;
    }
  }
}
</script>

<style lang="less" scoped>
.header-link {
    position: absolute;
    top:0;
    right:0;
    height:100%;
    padding:0 30px;
    font-size:30px;
  }
  .form-card {
    .amount-box {
      position:relative;
      .tip-box {
        position:absolute;
        left:0;
        bottom:30px;
        margin:0 30px;
      }
    }
    .item {
      padding:30px;
      background-color:#fff;
      & + .item {
        border-top:1px solid #ededf0;
      }
      &.momey-item {
        .label {
          margin-bottom: 50px;
        }
      }
      .label {
        font-size:32px;
        color:#292929;
      }
      .currency {
        &.currency-empty {
          color:#c0c3cc;
        }
        font-size:30px;
        color:#292929;
      }
    }
  }
  .form-btn {
    padding:30px;
    margin-top:60px;
  }

  .info-card {
    padding:40px;
    background-color:#fff;
    border-bottom:1px solid #ededf0;
    .avatar {
      width: 140px;
      height:140px;
      border-radius: 50%;
      overflow: hidden;

      img {
        display: block;
        width:100%;
        height: 100%;
      }
    }

    .name {
      .text-ellipsis();
      max-width:100%;
      margin-top:20px;
      font-size:32px;
      color:#292929;
    }
    .account {
      .text-ellipsis();
      max-width:100%;
      margin-top:20px;
      font-size:28px;
      color:#999;
    }
    .check {
      margin-top:30px;
      font-size:28px;
      color:#2086f9;

      .ok {
        color:#d39b00;
      }
    }
  }

  .check-name-box {
    display: flex;
    align-items: center;
    font-size:28px;
    width:100%;
    overflow: hidden;
    input {
      display: block;
      margin-top:20px;
      font-size:28px;
      flex:1;
      min-width:50%;
      height:70px;
      padding:0 10px;
      border-radius: 4px;
      border:1px solid #c0c3cc;
    }
    div {
      margin-left:40px;
      max-width:50%;
    }
  }
</style>
